package personal.leil.learning.bfs;

import personal.leil.learning.TreeNode;

import java.util.LinkedList;
import java.util.Queue;

/**
 * 二叉树的广度优先遍历
 * Created by Leil on 18.1.24
 */
public class BinaryTreeBFS {


    public static void breadthFirstSearch(TreeNode root) {
        if (root == null) {
            return;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while (!queue.isEmpty()) {
            TreeNode current = queue.poll();
            System.out.print(current.value + "  ");
            if (current.left != null) {
                queue.offer(current.left);
            }
            if (current.right != null) {
                queue.offer(current.right);
            }
        }
    }



    /********************* For Test *************************/

    public static void main(String[] args) {
        // 构建一个二叉树
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(4);
        root.left.right = new TreeNode(5);
        root.right.left = new TreeNode(6);
        root.right.right = new TreeNode(7);

        // 进行广度优先遍历
        System.out.println("广度优先遍历结果：");
        breadthFirstSearch(root);
        System.out.println();
    }




}
